package auth

import (
	"context"
	"geak/libs/conf"
	"geak/libs/ecode"
	"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
	"strings"

	"google.golang.org/grpc/status"
)

// TokenInfo 用户信息
//type TokenInfo struct {
//	ID    string
//	Roles []string
//}

// AuthInterceptor 认证拦截器，对以authorization为头部，形式为`bearer token`的Token进行验证
func AuthInterceptor(ctx context.Context) (context.Context, error) {
	//token, err := grpc_auth.AuthFromMD(ctx, "bearer")
	//if err != nil {
	//	return nil, err
	//}
	//tokenInfo, err := parseToken(token)
	//if err != nil {
	//	return nil, status.Errorf(codes.Unauthenticated, " %v", err)
	//}
	bid := metautils.ExtractIncoming(ctx).Get("x-jeak-bid")
	if bid == "" {
		return nil, status.Errorf(ecode.UnContainBid, "Request failed with bid")
	}
	if !strings.Contains(conf.Conf.App.Bid,bid)  {
		return nil, status.Errorf(ecode.UnContainBid, "Request failed with bid")
	}
	version := metautils.ExtractIncoming(ctx).Get("x-jeak-version")
	//使用context.WithValue添加了值后，可以用Value(key)方法获取值
	//newCtx := context.WithValue(ctx, tokenInfo.ID, tokenInfo)
	newCtx := context.WithValue(ctx,"bid", bid)
	newCtx = context.WithValue(newCtx,"version",version)
	return newCtx, nil
}

//解析token，并进行验证
//func parseToken(token string) (TokenInfo, error) {
//	var tokenInfo TokenInfo
//	if token == "grpc.auth.token" {
//		tokenInfo.ID = "1"
//		tokenInfo.Roles = []string{"admin"}
//		return tokenInfo, nil
//	}
//	return tokenInfo, errors.New("Token无效: bearer " + token)
//}
